//
//  FingerChineseAppDelegate.m
//  FingerChinese
//
//  Created by luar on 20/01/2010.
//  Copyright __MyCompanyName__ 2010. All rights reserved.
//

#import "FingerChineseAppDelegate.h"
#import "FingerChineseViewController.h"
#import "FlashCardViewController.h"
#import "ContentViewController.h"
#import "Content.h"
#import "HitArea.h"
#import "PageView.h"
#import "FlashCard.h"

@implementation FingerChineseAppDelegate

@synthesize window, navView, fingerViewController, flashViewController, contentViewController, curContent, nodeValue;

- (void)applicationDidFinishLaunching:(UIApplication *)application {    
    // Override point for customization after app launch
	
	fingerPageNo = 1;
	flashPageNo = 1;
	
	CGRect frame = [UIScreen mainScreen].bounds;
	window=[[UIWindow alloc] initWithFrame:frame];
	
	navView = [[UINavigationController alloc] initWithRootViewController:nil];
	navView.navigationBarHidden = YES;
	navView.navigationBar.barStyle = UIBarStyleBlackTranslucent;
	navView.delegate = self;

	contentViewController = [[ContentViewController alloc] initWithStyle:UITableViewStylePlain];
	nodeValue = [NSMutableString string];
    contentViewController.contentList = [[NSMutableArray array] retain];
	[navView pushViewController:contentViewController animated:NO];	
	fingerViewController = [[FingerChineseViewController alloc] initWithNibName:nil bundle:nil];
	flashViewController = [[FlashCardViewController alloc] initWithNibName:nil bundle:nil];

    [window addSubview:navView.view];
    [window makeKeyAndVisible];
	
	// set it in info.plist is more fast
	//[[UIApplication sharedApplication] setStatusBarHidden:YES];
	
	NSString *xmlPath = [[NSBundle mainBundle]
						 pathForResource:@"content"
						 ofType:@"xml"
						 inDirectory:@"/"];
	NSURL *url = [[NSURL alloc] initFileURLWithPath:xmlPath];
	NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
	[xmlParser setDelegate:self];
	[xmlParser parse];
	[url release];
	[xmlParser release];
		
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuClick:) name:@"MenuClick" object:nil];
}

- (void)applicationWillTerminate:(UIApplication *)application {
	// Save data if appropriate
	int screenNo;
	if (navView.visibleViewController == contentViewController) {
		screenNo = 0;
	} else if (navView.visibleViewController == fingerViewController) {
		screenNo = 1;
	} else if (navView.visibleViewController == flashViewController) {
		screenNo = 2;
	}
	NSString *state = [NSString stringWithFormat:@"%i_%i_%i", screenNo, [fingerViewController getPageNo], [flashViewController getPageNo]];
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *fileName = [NSString stringWithFormat:@"%@/state.txt", documentsDirectory];
	[state writeToFile:fileName atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];
	NSLog(@"applicationWillTerminate state:%@, paths:%@, documentDir:%@, fileName:%@", state, paths, documentsDirectory, fileName);
	[state release];
	[paths release];
	[documentsDirectory release];
	[fileName release];
}

#pragma mark -
#pragma mark XML Parsing

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName 
	attributes:(NSDictionary *)attributeDict {
	if([elementName isEqualToString:@"item"]) {
		Content *content = [[Content alloc] init];
		self.curContent = content;
		self.curContent.icon = [attributeDict objectForKey:@"icon"];
		self.curContent.isAlignCenter = ([[attributeDict objectForKey:@"center"] intValue] == 1);
		self.curContent.isFlashCard = ([[attributeDict objectForKey:@"isflashcard"] intValue] == 1);
		self.curContent.hideFromMenu = ([[attributeDict objectForKey:@"hide"] intValue] == 1);
		if (!self.curContent.isFlashCard) {
			self.curContent.pageNo = fingerPageNo;
			[fingerViewController.pickerViewArray addObject:[NSString stringWithFormat:@"Page %i", fingerPageNo]];
			fingerPageNo++;
			[fingerViewController.photoA addObject:[attributeDict objectForKey:@"file"]];
		}
		[content release];
	} else if ([elementName isEqualToString:@"title"]) {
		Content *content = [[Content alloc] init];
		self.curContent = content;
		self.curContent.isTitle = YES;
		[content release];
	} else if ([elementName isEqualToString:@"en"] || [elementName isEqualToString:@"cn"]) {
		isParsingFingerNode = YES;
		[self.nodeValue setString:@""];
	} else if ([elementName isEqualToString:@"cards"]) {
		isParsingFlashNode = YES;
	} else if ([elementName isEqualToString:@"card"]) {
		if (isParsingFlashNode) {
			self.curContent.pageNo = flashPageNo;
			isParsingFlashNode = NO;
		}
		[flashViewController.pickerViewArray addObject:[NSString stringWithFormat:@"Page: %i", flashPageNo]];
		flashPageNo++;
		FlashCard *fc = [[FlashCard alloc] init];
		fc.file = [attributeDict objectForKey:@"file"];
		fc.lb_en = [attributeDict objectForKey:@"en"];
		CGSize textSize = CGSizeMake(flashViewController.borderW, 20000);
		fc.lbHeight_en1 = [self calculateHeightOfTextFromWidth:flashViewController.lbSize textSize:textSize str:fc.lb_en];
		textSize = CGSizeMake(flashViewController.borderH, 20000);
		fc.lbHeight_en3 = [self calculateHeightOfTextFromWidth:flashViewController.lbSize textSize:textSize str:fc.lb_en];
		fc.isFaced = YES;
		fc.hasSound = ([[attributeDict objectForKey:@"nosound"] intValue] != 1);
		[flashViewController.cardA addObject:fc];
		[fc release];
	} else if ([elementName isEqualToString:@"categories"]) {
		if ([[attributeDict objectForKey:@"verticalScroll"] intValue] == 1) {
			NSLog(@"page is vertical scroll");
			[fingerViewController setIsHorizontalScroll:NO];
			[flashViewController setIsHorizontalScroll:NO];
		}
		if ([[attributeDict objectForKey:@"fingerPage"] intValue] > 0) {
			flashViewController.fingerPageNo = [[attributeDict objectForKey:@"fingerPage"] intValue];
		}
		if ([[attributeDict objectForKey:@"flashCard"] intValue] > 0) {
			fingerViewController.flashCardPageNo = [[attributeDict objectForKey:@"flashCard"] intValue];
			flashViewController.header_en = [attributeDict objectForKey:@"flashCard_label_en"];
			flashViewController.header_cn = [attributeDict objectForKey:@"flashCard_label_cn"];
		}
		if ([[attributeDict objectForKey:@"cardX"] intValue] > 0) {
			flashViewController.cardX = [[attributeDict objectForKey:@"cardX"] intValue];
		}
		if ([[attributeDict objectForKey:@"cardY"] intValue] > 0) {
			flashViewController.cardY = [[attributeDict objectForKey:@"cardY"] intValue];
		}
		if ([[attributeDict objectForKey:@"cardW"] intValue] > 0) {
			flashViewController.cardW = [[attributeDict objectForKey:@"cardW"] intValue];
		}
		if ([[attributeDict objectForKey:@"cardH"] intValue] > 0) {
			flashViewController.cardH = [[attributeDict objectForKey:@"cardH"] intValue];
		}
		contentViewController.title = [attributeDict objectForKey:@"title"];
	}
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if (isParsingFingerNode) {
        // If the current element is one whose content we care about, append 'string'
        // to the property that holds the content of the current element.
		[self.nodeValue appendString:string];
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	isParsingFingerNode = NO;
	if ([elementName isEqualToString:@"en"]) {
		NSScanner *scanner = [NSScanner scannerWithString:self.nodeValue];
		NSString *title;
		[scanner scanUpToCharactersFromSet:[NSCharacterSet illegalCharacterSet] intoString:&title];
		self.curContent.title_en = title;
		[self.nodeValue setString:@""];
	} else if ([elementName isEqualToString:@"cn"]) {
		NSScanner *scanner = [NSScanner scannerWithString:self.nodeValue];
		NSString *title;
		[scanner scanUpToCharactersFromSet:[NSCharacterSet illegalCharacterSet] intoString:&title];
		self.curContent.title_cn = title;
		[self calculateHeightForContent];
		[self.nodeValue setString:@""];
	} else if([elementName isEqualToString:@"item"]) {
		if (!self.curContent.hideFromMenu)
			[contentViewController.contentList addObject:self.curContent];
	}  else if([elementName isEqualToString:@"title"]) {
		if (!self.curContent.hideFromMenu)
			[contentViewController.contentList addObject:self.curContent];
	} else if([elementName isEqualToString:@"categories"]) {
		// XML Parsing is finished
		[self parseDone];
	}
}

- (void)parseDone {
	//[self.nodeValue release];
	[self.curContent release];
	[contentViewController.tableView reloadData];
	NSLog(@"parseDone %i", [contentViewController.contentList count]);
	
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSLog(@"parseDone paths count: %i", [paths count]);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *fileName = [NSString stringWithFormat:@"%@/state.txt", documentsDirectory];
	NSString *state = [[NSString alloc] initWithContentsOfFile:fileName usedEncoding:nil error:nil];
	if (state) {
		NSArray *stateA = [state componentsSeparatedByString:@"_"];
		NSLog(@"parseDone state: %@", stateA);
		//[stateA release];
		[state release];
		int screenNo = [[stateA objectAtIndex:0] intValue];
		fingerViewController.initPageNo = [[stateA objectAtIndex:1] intValue];
		flashViewController.initPageNo = [[stateA objectAtIndex:2] intValue];
		if (screenNo == 1) {
			[navView pushViewController:fingerViewController animated:NO];
		} else if (screenNo == 2) {
			[navView pushViewController:flashViewController animated:NO];
		}
	}
	//[fileName release];
	//[paths release];
	//[documentsDirectory release];	
}

#pragma mark -
#pragma mark UINavigationController Event

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)_fingerViewController animated:(BOOL)animated {
	NSLog(@"FingerChineseAppDelegate willShowViewController %@", _fingerViewController);
	if (_fingerViewController == contentViewController) {
		[contentViewController updateInterfaceOrientation];
		navView.navigationBar.alpha = 0.0;
		[navView setNavigationBarHidden:YES animated:NO];
		[[NSNotificationCenter defaultCenter] removeObserver:self name:@"PageTouchesBegan" object:nil];
	} else if (_fingerViewController == fingerViewController) {
		[fingerViewController updateInterfaceOrientation];
	} else if (_fingerViewController == flashViewController) {
		[flashViewController updateInterfaceOrientation];
	}
}
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)_fingerViewController animated:(BOOL)animated {
	NSLog(@"FingerChineseAppDelegate didShowViewController %@", _fingerViewController);
	if (_fingerViewController != contentViewController) {
		[navView setNavigationBarHidden:NO animated:NO];
		[UIView beginAnimations:nil context:nil];
		[UIView setAnimationDuration:0.5];
		navView.navigationBar.alpha = 1.0;
		[UIView commitAnimations];
		isNavBarShow = YES;
		[[NSNotificationCenter defaultCenter] removeObserver:self name:@"PageTouchesBegan" object:nil];
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pageTouchesBegan:) name:@"PageTouchesBegan" object:nil];
	}
}

- (void)pageTouchesBegan:(NSNotification *)notification {
	NSLog(@"touchPoint %i %@", isNavBarShow, [[[notification object] superview] superview]);
	if (isNavBarShow) {
		[UIView beginAnimations:nil context:nil];
		[UIView setAnimationDuration:0.5];
		//[UIView setAnimationDelegate:self];
		//[UIView setAnimationDidStopSelector:@selector(onNavBarShow:finished:context:)];
		navView.navigationBar.alpha = 0.0;
		[UIView commitAnimations];
		navView.navigationBar.userInteractionEnabled = NO;
		isNavBarShow = NO;
	} else {
		UIEvent *event = [[notification userInfo] objectForKey:@"event"];
		UITouch *touch = [[event allTouches] anyObject];
		CGPoint touchPoint = [touch locationInView:navView.navigationBar];
		BOOL canPlay;
		if ([[notification object] isKindOfClass:[PageView class]]) {
			canPlay = YES;
		} else if ([[notification object] isKindOfClass:[HitArea class]]) {
			HitArea *ha = [notification object];
			if (ha.canPlay) {
				canPlay = YES;
			}
		}
		if (touchPoint.y > 0 && touchPoint.y < navView.navigationBar.frame.size.height && canPlay) {
			[UIView beginAnimations:nil context:nil];
			[UIView setAnimationDuration:0.5];
			//[UIView setAnimationDelegate:self];
			//[UIView setAnimationDidStopSelector:@selector(onNavBarShow:finished:context:)];
			navView.navigationBar.alpha = 1.0;
			[UIView commitAnimations];
			navView.navigationBar.userInteractionEnabled = YES;
			isNavBarShow = YES;
		}
		NSLog(@"touchPoint %@ %f %f %f", [notification object], touchPoint.x, touchPoint.y, navView.navigationBar.frame.size.height);
	}
}

/*- (void)onNavBarShow:(NSString*)animationID finished:(NSNumber*)finished context:(void*)context {
	NSLog(@"onNavBarShow %@ %@ %@", animationID, finished, context);
}*/

#pragma mark -

- (void)calculateHeightForContent {
	int fontWidth;
	CGSize textSize;

	fontWidth = (!self.curContent.isTitle) ? contentViewController.cellWidth1 : contentViewController.titleWidth1;
	textSize = CGSizeMake(fontWidth, 20000);
	self.curContent.lbHeight_en1 = [self calculateHeightOfTextFromWidth:contentViewController.fontSize_en textSize:textSize str:self.curContent.title_en];
	self.curContent.lbHeight_cn1 = [self calculateHeightOfTextFromWidth:contentViewController.fontSize_cn textSize:textSize str:self.curContent.title_cn];
	self.curContent.cellHeight1 = self.curContent.lbHeight_en1+self.curContent.lbHeight_cn1+6;
	
	fontWidth = (!self.curContent.isTitle) ? contentViewController.cellWidth3 : contentViewController.titleWidth3;
	textSize = CGSizeMake(fontWidth, 20000);
	self.curContent.lbHeight_en3 = [self calculateHeightOfTextFromWidth:contentViewController.fontSize_en textSize:textSize str:self.curContent.title_en];
	self.curContent.lbHeight_cn3 = [self calculateHeightOfTextFromWidth:contentViewController.fontSize_cn textSize:textSize str:self.curContent.title_cn];
	self.curContent.cellHeight3 = self.curContent.lbHeight_en3+self.curContent.lbHeight_cn3+6;
	
	//NSLog(@"calculateHeightOfTextFromWidth %i %i %i %i", contentViewController.cellWidth3, contentViewController.fontSize_cn, self.curContent.cellHeight1, self.curContent.cellHeight3);
}

- (int)calculateHeightOfTextFromWidth:(int)fontSize textSize:(CGSize)textSize str:(NSString *)str {
	CGSize size = [str sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:textSize lineBreakMode:UILineBreakModeWordWrap];
	return size.height;
}

- (void)menuClick:(NSNotification *)notification {
	NSLog(@"menuClick %i %i %i", contentViewController.pageNo, contentViewController.isFlashCard, [navView.viewControllers count] );
	if ([notification object] == contentViewController) {
		if (!contentViewController.isFlashCard) {
			[navView pushViewController:fingerViewController animated:YES];
			[fingerViewController jumpPage:contentViewController.pageNo];
		} else {
			[navView pushViewController:flashViewController animated:YES];
			[flashViewController jumpPage:contentViewController.pageNo];
		}		
	} else if ([notification object] == fingerViewController) {
		[navView pushViewController:flashViewController animated:YES];
		//[flashViewController jumpPage:fingerViewController.flashCardPageNo];
	} else if ([notification object] == flashViewController) {
		[navView pushViewController:fingerViewController animated:YES];
		//[fingerViewController jumpPage:flashViewController.fingerPageNo];
	}

}

#pragma mark -

- (void)dealloc {
	[nodeValue release];
	[curContent release];
	[flashViewController release];
	[fingerViewController release];
	[contentViewController release];
    [navView release];
    [window release];
    [super dealloc];
}

@end
